package com.one.customer.dao;

import com.one.DBUtil;
import com.one.customer.model.Customer;
import java.sql.PreparedStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

public class CustomerDao {
    //更具会员名称来查询会员信息
    public Customer getCustomerByName(String username) {
        Connection conn = DBUtil.getConnection();
        String sql = "select * from tb_customer where user_name=?";
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            rs = ps.executeQuery();
            if (rs.next()) {
                Customer customer = new Customer();
                customer.setId(rs.getInt("id"));
                customer.setEmail(rs.getString("email"));
                customer.setMobile(rs.getString("mobile"));
                customer.setPassword(rs.getString("password"));
                customer.setReal_name(rs.getString("real_name"));
                customer.setReal_name(rs.getString("real_name"));
                customer.setUser_name(rs.getString("user_name"));
                return customer;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.closeResource(conn, ps, rs);
        }
        return null;
    }

    //根据用户名和密码添加用户信息
    public int addCustomer(String username, String password,String phone) {
//判断账号是否存在
        Customer customer = getCustomerByName(username);
        if (customer == null) {
            Connection conn = DBUtil.getConnection();
            String sql = "INSERT INTO `tb_customer` (`user_name`,`password`,`mobile`) VALUES(?,?,?)";
            PreparedStatement ps = null;
try{
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            ps.setString(3, phone);
//执行并更新新数据库，返回数据库中受影响的行数
            int num = ps.executeUpdate();
            return num;
        }catch(SQLException e){
            throw new RuntimeException(e);
        }finally{
            DBUtil.closeResource(conn, ps, null);
        }
    }else{
        //账号已存在，返回0表示失败
        return 0;
    }
}
}